﻿using System;
using System.Collections.Generic;
using System.Linq;

using ESoft.Core.Data.Service;
using ESoft.Core.Utils.Extensions;
using ESoft.Core.Web.Utils;
using ESoft.Core.Web.VO;
using ESoft.Portal.Areas.ContentManager.Data.Service;
using ESoft.Portal.Data.Domain.Entity;

using Microsoft.AspNetCore.Mvc;

namespace ESoft.Portal.Areas.ContentManager.ApiControllers
{
    [Route("api/content/article")]
    [ApiController]
    public class ArticleController : ControllerBase
    {
        private readonly IBaseService _baseService;
        private readonly IChannelService _channelService;
        public ArticleController(IBaseService baseService, IChannelService channelService)
        {
            _baseService = baseService;
            _channelService = channelService;
        }

        [Route("page")]
        [HttpGet]
        public object GetPageList([FromQuery]PageInput pageInput, [FromQuery]string keyword, [FromQuery]string channelId)
        {
            var channelList = new List<string> { };
            if (channelId.IsNotNullOrWhiteSpace())
            {
                channelList = _channelService.GetAllChannel(channelId).Select(x => x.ChannelId).ToList();
                channelList.Add(channelId);
            }
            User user = EnvUtils.GetCurrentUser(Request.HttpContext);
            List<Dictionary<string, object>> articleList = _baseService.QueryPageEntities<CContentArticleEntity>(pageInput,
                    x => x.OrgId == user.ShopId
                         && (keyword.IsNullOrEmpty() || x.Title.Contains(keyword)) &&
                                (channelList.Count == 0 || x.ChannelId.In(channelList)),
                    new SortVo { SortField = "CreateDatetime", SortWay = false })
                    .Select(x => new Dictionary<string, object>
                    {
                        { "articleId",x.ArticleId},
                        { "title",x.Title},
                        { "channelId",x.ChannelId},
                        { "channelName",""},
                        { "isHot",x.IsHot},
                        { "imageId",x.ImageId},
                        { "sort",x.Sort},
                        { "createDatetime",x.CreateDatetime}
                    }).ToList();

            foreach (var article in articleList.Where(article => article["channelId"].IsNotNull() &&
                                                      article["channelId"].ToString().IsNotNullOrWhiteSpace()))
            {
                var cc = _baseService.Find<CContentChannelEntity>(article["channelId"]);
                if (cc != null)
                    article["channelName"] = cc.ChannelName;
            }

            var count = _baseService.Count<CContentArticleEntity>(x => x.OrgId == user.ShopId
                                                                       && (keyword.IsNullOrEmpty() || x.Title.Contains(keyword))
                                                                      && (channelList.Count == 0 || x.ChannelId.In(channelList)));

            return ResponseResult.Success(new PageResult<Dictionary<string, object>>(articleList, count));
        }

        [Route("Query")]
        [HttpGet]
        public object Query()
        {
            User user = EnvUtils.GetCurrentUser(Request.HttpContext);
            var channelList = _baseService.QueryEntities<CContentChannelEntity>(x => x.OrgId == user.ShopId);
            return ResponseResult.Success(channelList);
        }


        [Route("addArticle")]
        [HttpPost]
        public object AddArticle([FromBody]dynamic input)
        {
            User user = EnvUtils.GetCurrentUser(Request.HttpContext);

            CRichTextEntity richText = new CRichTextEntity();
            string fullDetail = input.fullDetail;
            richText.TextContent = System.Text.Encoding.Default.GetBytes(fullDetail);
            _baseService.Add(richText);

            CContentArticleEntity channel = new CContentArticleEntity
            {
                ChannelId = input.channelId,
                OrgId = user.ShopId,
                Title = input.title,
                CreateDatetime = DateTime.Now,
                ImageId = input.imageId,
                IsHot = input.isHot,
                RichTextId = richText.RichTextId,
                Sort = input.sort,
                Url = input.url
            };
            _baseService.Add(channel);
            return ResponseResult.Success();
        }

        [Route("updateArticle")]
        [HttpPut]
        public object UpdateArticle([FromBody]dynamic input, [FromQuery]string articleId)
        {
            User user = EnvUtils.GetCurrentUser(Request.HttpContext);

            CRichTextEntity richText = new CRichTextEntity();
            string fullDetail = input.fullDetail;
            richText.TextContent = System.Text.Encoding.Default.GetBytes(fullDetail);
            _baseService.Add(richText);

            CContentArticleEntity channel = new CContentArticleEntity
            {
                ArticleId = articleId,
                ChannelId = input.channelId,
                OrgId = user.ShopId,
                Title = input.title,
                CreateDatetime = DateTime.Now,
                ImageId = input.imageId,
                IsHot = input.isHot,
                RichTextId = richText.RichTextId,
                Sort = input.sort,
                Url = input.url
            };
            _baseService.Update(channel);
            return ResponseResult.Success();
        }

        [Route("{articleId}")]
        [HttpGet]
        public object Get([FromRoute]string articleId)
        {
            User user = EnvUtils.GetCurrentUser(Request.HttpContext);
            var article = _baseService.Find<CContentArticleEntity>(articleId);
            var richText = _baseService.Find<CRichTextEntity>(article.RichTextId);
            var result = new Dictionary<String, object>
            {
                { "articleId",article.ArticleId},
                { "title",article.Title},
                { "channelId",article.ChannelId},
                { "channelName",""},
                { "isHot",article.IsHot},
                { "imageId",article.ImageId},
                { "sort",article.Sort},
                { "createDatetime",article.CreateDatetime},
                { "url",article.Url},
                {"fullDetail", System.Text.Encoding.Default.GetString(richText.TextContent) },
            };

            return ResponseResult.Success(result);
        }

        [HttpDelete]
        public object Delete([FromBody] dynamic dy)
        {
            string articleId = dy.articleId;
            User user = EnvUtils.GetCurrentUser(Request.HttpContext);
            _baseService.Delete<CContentArticleEntity>(articleId);
            return ResponseResult.Success();
        }
    }
}